/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.registration.web.controller;

import com.registration.RegistrationManager;
import com.registration.web.utils.JSONResponse;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 *
 * @author Usuario
 */
public abstract class AbstractConfiguradorController {
    private Logger LOGGER;
    private ObjectMapper objectMapper;
    protected abstract Logger getLogger();    
    
    @Autowired
    protected RegistrationManager registrationManager;

    public AbstractConfiguradorController() {
    }

    public void setRegistrationManager(RegistrationManager registrationManager) {
        this.registrationManager = registrationManager;
    }        
    
    @ExceptionHandler(value = Exception.class)
    public void handleException(Exception exception,
            HttpServletResponse response) throws IOException {
        getLogger().error(exception.getMessage(), exception);
        Object[] parametros = { exception.getMessage() };
        String mensaje = "Error";
        writeJsonResponse(response, mensaje);
    }

    @ExceptionHandler(value = ObjectRetrievalFailureException.class)
    public void handleException(ObjectRetrievalFailureException exception, HttpServletResponse response) {
        String mensaje = "Error";
        writeJsonResponse(response, mensaje);
    }

    @ExceptionHandler(value = DataIntegrityViolationException.class)
    public void handleException(DataIntegrityViolationException exception, HttpServletResponse response) {
        String mensaje = "Error";
        writeJsonResponse(response, mensaje);
    }
    
    @ExceptionHandler(value = ConstraintViolationException.class)
    public void handleException(ConstraintViolationException exception, HttpServletResponse response) {
    	String mensaje = "Error";
        writeJsonResponse(response, mensaje);
    }    

    protected void writeJsonResponse(HttpServletResponse response, String message) {
        boolean exitoso = false;
        JSONResponse<String> jsonResponse = new JSONResponse<String>(message, message, exitoso);
        response.setContentType("application/json");
        try {
            Writer out = response.getWriter();
            objectMapper.writeValue(out, jsonResponse);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }    
}
